package com.itealabs.postjson.ext;

import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.itealabs.postjson.JsonCall;
import com.itealabs.postjson.JsonRequest;
import com.itealabs.postjson.JsonRequestWaiter;
import com.itealabs.postjson.JsonResponse;
import com.itealabs.postjson.JsonReturn;
import com.itealabs.postjson.JsonReturn.State;

/**
 * Logs JsonRequest info.
 * @version $Id: JsonRequestLogging.java 13 2010-04-23 05:50:41Z iteahere $
 * @author itea
 * 2010-4-22
 */
public class JsonRequestLogging implements JsonRequestWaiter {

	private Log log = LogFactory.getLog(JsonRequestLogging.class);
	
	private JsonRequestWaiter target;
	
	public void service(JsonRequest jsonReq, JsonResponse jsonResp,
			Map<String, Object> ctx) {

		log.info(jsonReq.getUserAgent());
		target.service(jsonReq, jsonResp, ctx);
		for(JsonReturn rt : jsonResp.getReturns())
			
			if(State.ERROR.equals(rt.getState()))
				log.error(getCallByIdx(rt.getIdx().intValue(), jsonReq)
						.getMethod(), (Throwable)rt.getResult());
		
			else if(State.EXCEPTION.equals(rt.getState()))
				log.warn(getCallByIdx(rt.getIdx().intValue(), jsonReq)
						.getMethod(), (Throwable)rt.getResult());
	}

	protected JsonCall getCallByIdx(int idx, JsonRequest jsonReq) {
		JsonCall c = jsonReq.getCalls().get(idx);
		return c;
	}
	
	public void setTarget(JsonRequestWaiter target) {
		this.target = target;
	}

	public JsonRequestWaiter getTarget() {
		return target;
	}

}
